<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
      <!-- 卡片区域 -->
     <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" round>添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, i1) in scope.row.children"
            :key="item1.id" :class="['border-b', i1 === 0 ? 'border-t': '', 'v-center']">
              <!-- 一级权限区域 -->
              <el-col :span="5">
                <el-tag closable  @close='rolesDeleteById(scope.row, item1.id)'>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限合并的区域 -->
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children"
                :key="item2.id" :class="[ i2 === 0 ? '' : 'border-t', 'v-center' ]">
                  <!-- 二级权限区域  -->
                  <el-col :span="6">
                    <el-tag type="success" closable  @close='rolesDeleteById(scope.row, item2.id)'>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限区域 -->
                    <el-tag v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close='rolesDeleteById(scope.row, item3.id)'>
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色管理" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRightDilog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 点击分配权限的弹出框 -->
    <el-dialog
      title="商品信息"
      :visible.sync="showRightDialogVisible"
      width="50%" @close='setDefKeysClose'>
      <el-tree :data="rightsList" :props="defaultProps" show-checkbox node-key='id' default-expand-all :default-checked-keys='defKeys' ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRoleRigths">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      showRightDialogVisible: false,
      rightsList: [],
      defaultProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: ''

    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.rolesList = res.data
    },
    // 根据ID删除用户权限
    async rolesDeleteById (role, rightId) {
      const resultConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (resultConfirm !== 'confirm') return this.$message.info('您取消了删除')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // this.getRolesList()
      // 如果直接调用上面的方法，会造成页面的重绘，页面会刷新，这不符合需求
      // 我们需要的是：删除以后，展开行不闭合
      // 因为 role 和 scope.row 在同一个内存空间，role 改变以后， scope.row 也会改变
      // 因此我们将后台返回的最新的权限数据赋值给 role.children 即可
      role.children = res.data
    },
    // 点击分配权限的处理函数
    async showRightDilog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.rightsList = res.data
      this.getDefKeys(role, this.defKeys)
      this.showRightDialogVisible = true
    },
    // 定义一个递归函数，将三级权限id全部递归出来，并保存到defKeys中
    getDefKeys (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => this.getDefKeys(item, arr))
    },
    // 监听关闭对话框时清空递归的数组
    setDefKeysClose () {
      this.defKeys = []
    },
    // 点击确定时为角色分配权限
    async allRoleRigths () {
      // 1需要拿到所有全选和半选的id
      const allId = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
      const strId = allId.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: strId })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.showRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.border-t{
  border-top: 1px solid #eee;
}
.border-b{
  border-bottom: 1px solid #eee;
}
.el-tag{
  margin: 5px;
}
.v-center{
  display: flex;
  align-items: center;
}
</style>
